﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB;
using MongoDB.Linq;
using MongoDB.Connections;
namespace PicturePortfolio.Persistance
{
    public class GenericRepository:IRepository
    {
        public GenericRepository()
        {
 
        }

        Mongo _mongoDb=null;
        private IMongoCollection<TEntity> GetQuery<TEntity>() where TEntity : class
        {
            if (_mongoDb == null)
            {
                _mongoDb = new Mongo();
                _mongoDb.Connect();
            }
            return DataBase.GetCollection<TEntity>(typeof(TEntity).Name + "s");
        }

        IMongoDatabase db = null;
        private IMongoDatabase DataBase
        {
            get
            {
                if (db == null)
                {
                    db = _mongoDb.GetDatabase("Protfolio");
                }
                return db;
            }
        }

        public IList<TEntity> GetAll<TEntity>() where TEntity : class
        {
            try
            {
                return GetQuery<TEntity>().Linq().ToList<TEntity>();
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public IList<TEntity> Find<TEntity>(System.Linq.Expressions.Expression<Func<TEntity, bool>> criteria) where TEntity : class
        {
            return this.GetQuery<TEntity>().Linq<TEntity>().Where(criteria).ToList<TEntity>();
        }

        public TEntity Single<TEntity>(System.Linq.Expressions.Expression<Func<TEntity, bool>> criteria) where TEntity : class
        {
            return this.GetQuery<TEntity>().Linq<TEntity>().Single(criteria);
        }

        public TEntity First<TEntity>(System.Linq.Expressions.Expression<Func<TEntity, bool>> criteria) where TEntity : class
        {
            return this.GetQuery<TEntity>().Linq<TEntity>().First(criteria);
        }

        public void Add<TEntity>(TEntity entity) where TEntity : class
        {
            this.GetQuery<TEntity>().Save(entity);
        }

        public void Delete<TEntity>(TEntity entity) where TEntity : class
        {
            this.GetQuery<TEntity>().Remove(entity);
            
        }

        public void Delete<TEntity>(IEnumerable<TEntity> entites) where TEntity : class
        {
            throw new NotImplementedException();
        }

        public void Update<TEntity>(TEntity entity, TEntity old) where TEntity : class
        {
            this.GetQuery<TEntity>().Update(entity, old, UpdateFlags.None, true);
        }
    }
}
